import webapp2
import jinja2
import os
import logging
import re

from model import Course

JINJA_ENVIRONMENT = jinja2.Environment(loader=jinja2.FileSystemLoader(os.path.dirname(__file__)))
course_code_input_filter = re.compile('[\W_]+')

class MainPage(webapp2.RequestHandler):
	def get(self):
		respond(self,{})

class CourseChecker(webapp2.RequestHandler):
	def get(self):
		course_code=self.request.get('code')
		if course_code is not None:
			course_code = course_code_input_filter.sub('',course_code).upper()
		template_values = {'code': course_code}
		logging.debug("course code: "+course_code)
		course = None
		if course_code:
			course = Course.get_by_key_name(course_code,parent=None)

		if course is not None:
			course.views = course.views+1;
			course.put()
			template_values['course'] = course
		else:
			template_values['error'] = "Duuuh.. There is not such a module: " + course_code
		respond(self,template_values)

def respond(request, template_values):
	template = JINJA_ENVIRONMENT.get_template('index.html')
	request.response.write(template.render(template_values))